import Router from "./index";
import Layout from "../layout/index.vue";
import {type RouteRecordRaw } from 'vue-router';


export type RouteMeta = {  
    title: string;  
    icon?: string;  
    affix?: boolean;  
    // 可以在这里添加其他你希望明确类型的属性  
    [key: string]: any; // 索引签名允许任意属性  
}  
/**
 * 格式限制
 * */
export type RouteItem = {
    ID?: string,
    parentID?: string,
    name: string,
    path: string,
    component?: string | Function | undefined,
    url?: string,
    redirect?: string,
    hidden?: boolean,
    isKeepAlive?: boolean,
    meta?: RouteMeta,
    children?: Array<RouteItem>,
    [key: string] : any,
}

/**
 * 动态设置路由
 * @author zs.duan
 * @date 2024-08-16
 * @param {RouteItem[]} routerList - RouteItem
 * @returns {boolean} 是否成功
 * */
function setRouter(routerList: RouteItem[]): boolean {
    if (!routerList) return false;
    let newRouterList: RouteRecordRaw[] = [];
    const setRouterList = (routerList: RouteItem[]): RouteItem[] | undefined => {
        routerList.forEach(item => {
            if (item.children && item.children.length > 0) {
                item.children = setRouterList(item.children);
            }
            if (item.component && item.component !== 'Layout') {
                item.component = loadView(item.component);
            }
            if (item.component === 'Layout') {
                item.component = Layout;
            }
        })
        return routerList;
    }
    setRouterList(routerList);
    routerList.forEach(item => {
        Router.addRoute(item as RouteRecordRaw);
    })
    return true
}


/**
 * 路由懒加载
 * @author zs.duan
 * @date 2024-08-16
 * @param {String } view 路由路径
 * @returns {Function} 路由组件
 * */
function loadView(view: string | Function) {
    if (!view) return;
    if (typeof view === 'function') return view;
    return import.meta.glob('../views/**/*.vue')[`../views/${view}.vue`];
}

export default setRouter;